package com.tgy.atomic;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @Author: tgy
 * @Date: 12/8/20 4:34 PM
 */
public class MyLock implements Lock {

    private transient volatile int status;

    private static long loc;

    private static Unsafe unsafe;

    static  {

        try {
            //这个由于jvm类加载器的保护作用，不能获取
//            unsafe = Unsafe.getUnsafe();

            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
            loc = unsafe.objectFieldOffset(MyLock.class.getDeclaredField("status"));
        } catch (Exception e) {
            throw new Error(e);
        }

    }


    @Override
    public void lock() {

        while (true) {

            int except = status;
            if (except == 0 && unsafe.compareAndSwapInt(this,loc,except,1)) {
                break;
            }
        }
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {

    }

    @Override
    public boolean tryLock() {

        int except = status;
        if (except == 0 && unsafe.compareAndSwapInt(this,loc,except,1)) {

            return true;
        }

        return false;
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }

    @Override
    public void unlock() {

        status = 0;
    }

    @Override
    public Condition newCondition() {
        return null;
    }
}
